package com.example.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class PreferencesService {
	private Context context;
	
	public PreferencesService(Context context){
		this.context=context;
	}
	
	@SuppressLint("CommitPrefEdits")
	public void save(Map<String,Object> map) {
		SharedPreferences preferences = context.getSharedPreferences(this.getClass().getSimpleName(), Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		for(Entry<String,Object> entry: map.entrySet()){
			putValueToEditor(editor,entry);
		}
		editor.commit();
	}
	
	
	@SuppressWarnings("unchecked")
	private void putValueToEditor(Editor editor,Entry<String,Object> entry){
		String key = entry.getKey();
		Object value = entry.getValue();
		if(value instanceof String){
			editor.putString(key, (String) value);
		}else if(value instanceof Integer){
			editor.putInt(key, ((Integer) value).intValue());
		}else if(value instanceof Long){
			editor.putLong(key, (Long) value);
		}else if(value instanceof Boolean){
			editor.putBoolean(key, (Boolean) value);
		}else if(value instanceof Float){
			editor.putFloat(key, (Float) value);
		}else{
			editor.putStringSet(key, ((Set<String>) value));
		}
		
	}

	public Map<String, ?> getPreferences() {
		SharedPreferences preferences = context.getSharedPreferences(this.getClass().getSimpleName(), Context.MODE_PRIVATE);
		Map<String, ?> map = preferences.getAll();
		return map;
	}

}
